<template>
  <div class="discover-page">
    <!-- 顶部通知区域 -->
    <div class="notice-section">
      <h3>消息中心</h3>
      <div class="notice-grid">
        <div class="notice-item">
          <van-icon name="bell" class="notice-icon" />
          <span>系统消息</span>
        </div>
        <div class="notice-item">
          <van-icon name="notes-o" class="notice-icon" />
          <span>订单消息</span>
        </div>
      </div>
    </div>

    <!-- 直播预告区域 -->
    <div class="live-preview">
      <div class="preview-header">
        <span class="title">预约直播</span>
        <span class="subtitle">全品类鉴定 免费鉴宝</span>
      </div>
    </div>

    <!-- 聊天列表 -->
    <div class="chat-list">
      <!-- 空状态 -->
      <div v-if="chatList.length === 0" class="empty-state">
        <van-empty description="暂无消息" />
      </div>

      <div 
        v-for="chat in chatList" 
        :key="chat.userId"
        class="chat-item"
        @click="goToChat(chat)"
      >
        <div class="chat-avatar">
          <van-badge :content="chat.unreadCount || ''" :show="chat.unreadCount > 0">
            <van-image
              :src="chat.avatar"
              fit="cover"
              round
              width="40"
              height="40"
              :error="defaultAvatar"
            />
          </van-badge>
        </div>
        
        <div class="chat-info">
          <div class="chat-header">
            <span class="chat-name">{{ chat.name }}</span>
            <span class="chat-time">{{ formatTime(chat.lastMessage?.time) }}</span>
          </div>
          <div class="chat-content">
            <span class="last-message">{{ chat.lastMessage?.content || '' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 直播列表 -->
    <div class="live-list">
      <div v-for="(item, index) in liveList" :key="index" class="live-item">
        <van-image
          :src="item.avatar"
          class="live-avatar"
          round
          fit="cover"
        />
        <div class="live-info">
          <div class="live-name">{{ item.name }}</div>
          <div class="live-status">{{ item.status }}</div>
        </div>
        <div class="live-time">{{ item.time }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { tim, TIM } from '@/tim'

const router = useRouter()
const chatList = ref([])
const defaultAvatar = 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'

// 模拟直播表数据
const liveList = ref([
  {
    name: '秦和田玉',
    status: '在的',
    time: '1小时前',
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  },
  {
    name: '鑫源堂',
    status: '在的',
    time: '1小时前',
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  },
  {
    name: '湘乐记',
    status: '在的',
    time: '1小时前',
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
  }
])

// 获取会话列表
const getConversationList = async () => {
  try {
    const { data } = await tim.getConversationList()
    chatList.value = data.conversationList.map(conv => ({
      userId: conv.userProfile.userID,
      name: conv.userProfile.nick || conv.userProfile.userID,
      avatar: conv.userProfile.avatar || defaultAvatar,
      unreadCount: conv.unreadCount,
      lastMessage: {
        content: conv.lastMessage?.payload?.text || '',
        time: conv.lastMessage?.time * 1000
      }
    }))
  } catch (error) {
    console.error('获取会话列表失败:', error)
    showToast('获取消息列表失败')
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  
  if (date.toDateString() === now.toDateString()) {
    return `${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
  }
  
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天'
  }
  
  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }
  
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
}

// 清除未读消息
const clearUnreadCount = async (conversationID) => {
  try {
    await tim.setMessageRead({ conversationID })
  } catch (error) {
    console.error('清除未读消息失败:', error)
  }
}

// 跳转到聊天页面
const goToChat = async (chat) => {
  // 清除未读消息
  if (chat.unreadCount > 0) {
    await clearUnreadCount(`C2C${chat.userId}`)
  }
  
  router.push({
    path: '/chat',
    query: {
      userId: chat.userId,
      userName: chat.name
    }
  })
}

onMounted(async () => {
  await getConversationList()
  
  // 监听新消息，更新会话列表
  tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, async () => {
    await getConversationList()
  })
})
</script>

<style scoped>
.discover-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

.notice-section {
  background: #fff;
  padding: 16px;
}

.notice-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
}

.notice-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.notice-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f8f8;
  padding: 16px;
  border-radius: 8px;
}

.notice-icon {
  font-size: 24px;
  color: #ee0a24;
  margin-bottom: 8px;
}

.live-preview {
  margin-top: 12px;
  background: #fff;
  padding: 12px 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-header .title {
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

.preview-header .subtitle {
  font-size: 12px;
  color: #999;
}

.chat-list {
  margin-top: 12px;
  background: #fff;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  margin-right: 12px;
  flex-shrink: 0;
  position: relative;
}

.chat-info {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.chat-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.chat-time {
  font-size: 12px;
  color: #999;
}

.chat-content {
  font-size: 12px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.live-list {
  margin-top: 1px;
  background: #fff;
}

.live-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.live-avatar {
  width: 40px;
  height: 40px;
  margin-right: 12px;
}

.live-info {
  flex: 1;
}

.live-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.live-status {
  font-size: 12px;
  color: #999;
}

.live-time {
  font-size: 12px;
  color: #999;
}

:deep(.van-badge) {
  --van-badge-background-color: #ee0a24;
  --van-badge-font-size: 12px;
  --van-badge-padding: 2px 6px;
  position: absolute;
  top: -6px;
  right: -6px;
}
</style> 